package cn.iocoder.yudao.module.promotion.fod.service;

import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.promotion.fod.convert.FirstOrderDiscountNewUserConvert;
import cn.iocoder.yudao.module.promotion.fod.dao.FirstOrderDiscountNewUserMapper;
import cn.iocoder.yudao.module.promotion.fod.pojo.po.FirstOrderDiscountNewUser;
import cn.iocoder.yudao.module.promotion.fod.pojo.vo.FirstOrderDiscountNewUserVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 平台首单优惠（新用户） Service 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Service
@Validated
public class FirstOrderDiscountNewUserServiceImpl extends FirstOrderDiscountInternalBaseService<FirstOrderDiscountNewUser, FirstOrderDiscountNewUserVO> implements FirstOrderDiscountNewUserService {
    private final Lock lock = new ReentrantLock();
    @Resource
    private FirstOrderDiscountNewUserMapper firstOrderDiscountNewUserMapper;

    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private MemberUserApi memberUserApi;

    @Override
    protected FirstOrderDiscountNewUserMapper getInjectedMapper() {
        return firstOrderDiscountNewUserMapper;
    }

    @Override
    public FirstOrderDiscountNewUserVO convertToViewObject(FirstOrderDiscountNewUser entity) {
        return FirstOrderDiscountNewUserConvert.INSTANCE.convert(entity);
    }

    @Override
    public FirstOrderDiscountNewUser getOrCreate(Long userId) {
        Assertions.isTrue(userId != null && userId > 0, "未获取到 userId");
        try {
            lock.lock();
            FirstOrderDiscountNewUser entity = getInjectedMapper().selectOne(FirstOrderDiscountNewUser::getUserId, userId);
            if (entity == null) {
                UserSimpleVO user = memberUserApi.validateUser(userId);
                entity = new FirstOrderDiscountNewUser();
                entity.setUserId(userId);
                // 当日注册的用户才默认为未使用
                entity.setUsed(DateUtils.differentDays(LocalDateTime.now(), user.getCreateTime()) > 1);
                getInjectedMapper().insert(entity);
            }
            return entity;
        } finally {
            lock.unlock();
        }
    }

}